using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.Security.Permissions;
using MagnoliaTableAdapters;


public partial class ReportTasks : System.Web.UI.Page
{
    static DataTable dtResults = new DataTable();
    static string pageResultStr = "";
    static string reportResultStr = "";

    protected override void Render(HtmlTextWriter writer)
    {
        // Write the HTML into this string builder
        StringBuilder sb = new StringBuilder();
        HtmlTextWriter hWriter = new HtmlTextWriter(new StringWriter(sb));
        base.Render(hWriter);

        // Store to a string
        pageResultStr = sb.ToString();

        // Write it back to the server's HTTP Stream -// *** skip this if you don't want to display the rendered content
        writer.Write(pageResultStr);
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Reporting - Tasks";
        
        // Add calendar to date fields
        TextBox_DateFrom.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateFrom.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");

        Btn_RunReport.Attributes.Add("onfocus", "cs_blur();");
        Btn_Reset.Attributes.Add("onfocus", "cs_blur();");
        Btn_Print.Attributes.Add("onclick", "window.print();");
        Btn_ExportCSV.Attributes.Add("onclick", "showExportPopup();");

        Lbl_Messages.Text = "All report parameters are optional.  If desired, search for an asset and provide any other report parameters before clicking \"Run Report\" to view the results";

        if (!Page.IsPostBack)
        {
            // set export filepath
            //String FileName = Convert.ToString(Page.Title) + ".csv";
            ExportFileName.Value = Convert.ToString(Page.Title) + ".doc";

            // Load task type list
            Magnolia.TASKOPTIONDataTable TaskOptions = new Magnolia.TASKOPTIONDataTable();
            TASKOPTIONTableAdapter TaskAdapter = new TASKOPTIONTableAdapter();
            TaskAdapter.Fill(TaskOptions);

            DDList_TaskTypes.DataSource = TaskOptions;
            DDList_TaskTypes.DataTextField = TaskOptions.NameColumn.ColumnName;
            DDList_TaskTypes.DataValueField = TaskOptions.IDColumn.ColumnName;
            DDList_TaskTypes.DataBind();

            ListItem taskOptionDefault = new ListItem();
            taskOptionDefault.Value = "0";
            taskOptionDefault.Text = "All Task Types";
            DDList_TaskTypes.Items.Insert(0, taskOptionDefault);
            DDList_TaskTypes.SelectedIndex = -1;

            // Load user list
            Magnolia.USERDataTable Users = new Magnolia.USERDataTable();
            USERTableAdapter UserAdapter = new USERTableAdapter();
            UserAdapter.Fill(Users);

            DDList_Users.DataSource = Users;
            DDList_Users.DataTextField = Users.UserNameColumn.ColumnName;
            DDList_Users.DataValueField = Users.IDColumn.ColumnName;
            DDList_Users.DataBind();

            ListItem userDefault = new ListItem();
            userDefault.Value = "0";
            userDefault.Text = "All Users";
            DDList_Users.Items.Insert(0, userDefault);
            DDList_Users.SelectedIndex = -1;

            DDList_Users.Items.Remove(DDList_Users.Items.FindByText("System"));
        }
    }

    protected void Btn_RunReport_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            // Open connection to db
            conn.Open();

            string sProc = "sproc_WEB_ReportTasks";
            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@AssetID";
            if (ListBox_Results.SelectedIndex < 1)
            {
                param.Value = -1;
            }
            else
            {
                param.Value = Convert.ToInt32(ListBox_Results.SelectedValue);
            }
            param.DbType = DbType.Int32;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@TaskOptionID";
            if (DDList_TaskTypes.SelectedIndex < 1)
            {
                param.Value = -1;
            }
            else
            {
                param.Value = Convert.ToInt32(DDList_TaskTypes.SelectedValue);
            }
            param.DbType = DbType.Int32;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@TaskUserID";
            if (DDList_Users.SelectedIndex < 1)
            {
                param.Value = -1;
            }
            else
            {
                param.Value = Convert.ToInt32(DDList_Users.SelectedValue);
            }
            param.DbType = DbType.Int32;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateStart";
            if (TextBox_DateFrom.Text.Trim().Length == 0)
            {
                param.Value = Convert.ToDateTime("1/1/1900 12:00 AM");
            }
            else
            {
                param.Value = Convert.ToDateTime(TextBox_DateFrom.Text);
            }
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateEnd";
            if (TextBox_DateTo.Text.Trim().Length == 0)
            {
                param.Value = Convert.ToDateTime("1/1/2100 12:00 AM");
            }
            else
            {
                param.Value = Convert.ToDateTime(TextBox_DateTo.Text);
            }
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            //DataTable dtResults = new DataTable();
            dtResults.Columns.Clear();
            dtResults.Rows.Clear();

            SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
            sqlAdapter.Fill(dtResults);

            //conn.Close();

            if (dtResults.Rows.Count == 0)
            {
                Lbl_Messages.Text = "The given report parameters returned no results";
                Lbl_Messages.Visible = true;
                Btn_Print.Enabled = false;
                Btn_ExportCSV.Enabled = false;
                GridView_Results.Visible = false;
            }
            else
            {
                GridView_Results.DataSource = dtResults;
                GridView_Results.DataBind();
                GridView_Results.Visible = true;
                //GridView_Results.FooterRow.Cells[2].Style["text-align"] = "right";
                GridView_Results.FooterRow.Cells[0].Text = "Total: ";
                GridView_Results.FooterRow.Cells[0].Text += Convert.ToString(GridView_Results.Rows.Count);
                Lbl_Messages.Visible = false;
                Btn_Print.Enabled = true;
                Btn_ExportCSV.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            //Utilities.SendErrorLogEmail(ex);  WGO: !!! Unable to find library
            throw ex;
        }
        finally
        {
            conn.Close();
        }

    }
    protected void Btn_Reset_Click(object sender, EventArgs e)
    {
        TextBox_DateFrom.Text = "";
        TextBox_DateTo.Text = "";
        DDList_Users.SelectedIndex = -1;
        DDList_TaskTypes.SelectedIndex = -1;
        ListBox_Results.Items.Clear();
    }

    protected void Btn_Search_Click(object sender, EventArgs e)
    {
        // query to get a list of items
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_GetListAsset";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@XML";
            param.Value = Session["ListSearchString"];
            param.DbType = DbType.Xml;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@IncludeDisabled";
            param.Value = Convert.ToBoolean(Session["ListSearchIncludeDisabled"]);
            param.DbType = DbType.Boolean;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            XmlReader xReader = cmd.ExecuteXmlReader();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(xReader);
            xReader.Close();

            XmlNodeList nodes = xDoc.SelectNodes("//ASSET");
            foreach (XmlNode xNode in nodes)
            {
                ListItem item = new ListItem();
                item.Text = Convert.ToString(xNode.Attributes["Name"].InnerXml);
                item.Value = Convert.ToString(xNode.Attributes["ID"].InnerXml);
                try
                {
                    item.Attributes.Add("label", Convert.ToString(xNode.Attributes["CreatedOn"].InnerXml));
                }
                catch (Exception exception)
                {
                    String err = exception.Message;
                }

                ListBox_Results.Items.Add(item);
            }
        }
        catch (Exception exception)
        {
            String err = exception.Message;
        }
        finally
        {
            conn.Close();
        }
    }

    protected void ExportGridToCSV()
    {
        // Create the CSV file to which grid data will be exported
        String FileName = Convert.ToString(Page.Title) + ".csv";
        String ExportPath = Server.MapPath("Exports");
        String FilePath = ExportPath + "\\" + FileName;
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        StreamWriter sw = new StreamWriter(FilePath, false);
        // First we will write the headers.
        int iColCount = dtResults.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dtResults.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dtResults.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

    protected void WriteReportToFile()
    {
        // Create the file to which data will be exported
        String FileName = Convert.ToString(Page.Title) + ".doc";
        String ExportPath = Server.MapPath("Exports");
        String FilePath = ExportPath + "\\" + FileName;
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        StreamWriter sw = new StreamWriter(FilePath, false);

        // Get Report From Page string
        String startIndexStr = "<div class=\"reportResults\">";
        String endIndexStr = "</table>";

        int startIndex = pageResultStr.IndexOf(startIndexStr);
        int endIndex = pageResultStr.IndexOf(endIndexStr);
        reportResultStr = pageResultStr.Substring(startIndex, endIndex - startIndex + 8);
        reportResultStr += "</div></div>";

        sw.Write(reportResultStr);
        sw.Close();
    }

    protected void Btn_ExportCSV_Click(object sender, EventArgs e)
    {
        WriteReportToFile();
        //ExportGridToCSV();
    }
}
